-- UIRankingList
-- Create by huanghr
-- 排行榜界面

-- UIRankingList 继承自layer
UIRankingList = class("UIRankingList", function()
    return cc.Layer:create();
end);

function UIRankingList.create(dungeonId)
    return UIRankingList.new(dungeonId);
end

-- 构造函数
function UIRankingList:ctor(dungeonId)
    self:setName("UIRankingList");

    local node = cc.CSLoader:createNode("layout/dungeon/RankingList.csb");
    self:addChild(node);
    self.node = node;
    self.dungeonId = dungeonId;
    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 注册点击按钮事件
    self:registerTouchEvent();

    -- 注册事件回调函数
    self:registerEventCallback();

    -- 排行榜飞入效果标示
    self.flyFlag = true;

    -- 初始化排行榜
    self:init(true);

    -- 重绘
    self:redraw();

    self:resize();
end

function UIRankingList:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册点击事件
function UIRankingList:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIRankingList");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 修改国籍
    local btnChange = findChildByName(self.node, "BT/btn_change_nation");
    local function onChangeNationClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            closeFormByName("UINationSelect");
            local uiForm = UINationSelect.create(self.dungeonId);
            UIMgr.getCurrentScene():addForm(uiForm);
        end
    end
    btnChange:addTouchEventListener(onChangeNationClick);
    TextStyleM.setTextStyle(btnChange, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnChange:setTitleText(getLocStr("btn_text_change_nation"));

    -- 注册排行榜图标点击事件
    local sdkLeaderoardImg = findChildByName(self.node, "BT/sdk_leaderboad");
    sdkLeaderoardImg:setTouchEnabled(true);

    local function onGoogleLeaderboardClick(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            sdkLeaderoardImg:runAction(cc.ScaleTo:create(0.05, 0.94));
        elseif eventType == ccui.TouchEventType.canceled then
            sdkLeaderoardImg:runAction(cc.ScaleTo:create(0.05, 1));
        elseif eventType == ccui.TouchEventType.ended then
            sdkLeaderoardImg:runAction(cc.ScaleTo:create(0.05, 1));
            -- 获取关卡编号
            local areaId = self.dungeonId;
            if PUBLISH_PLATFORM == PUBLISH_TYPE_GOOGLE_PLAY then
                local leaderboardId = GoogleLeaderboardM.queryIdbyField("area_id", areaId);
                if leaderboardId then
                    if not get3rdAccountLoginInfo(CHANNEL_GOOGLE) then
                        self.needShowSdkLeaderboard = true;
                        showGoogleLogin();
                        return;
                    end

                    -- 显示google排行榜
                    GoogleLeaderboardM.displayLeaderboard(leaderboardId);
                end
            elseif PUBLISH_PLATFORM == PUBLISH_TYPE_AMAZON then
                local leaderboardId = AmazonLeaderboardM.queryIdbyField("area_id", areaId);
                if leaderboardId then
                    if not get3rdAccountLoginInfo(CHANNEL_AMAZON) then
                        self.needShowSdkLeaderboard = true;
                        showAmazonLogin();
                        return;
                    end

                    -- 显示亚马逊排行榜
                    AmazonLeaderboardM.displayLeaderboard(leaderboardId);
                end
            end
        end
    end

    sdkLeaderoardImg:addTouchEventListener(onGoogleLeaderboardClick);
end

-- 是否显示sdk排行榜
function UIRankingList:isShowSdkLeaderboard()
    if PUBLISH_PLATFORM == PUBLISH_TYPE_GOOGLE_PLAY and
       GoogleLeaderboardM.isLeaderboardOpen() then
        return true;
    end

    if PUBLISH_PLATFORM == PUBLISH_TYPE_AMAZON and
       AmazonLeaderboardM.isLeaderboardOpen() then
        return true;
    end

    return false;
end

-- 重绘界面
function UIRankingList:redraw()
    -- 重绘排行榜标题
    local node = self.node;
    local titleLabel = findChildByName(self.node, "CT/title_bg/title");
    local dungeonName = DungeonAreaM.query(DungeonAreaM.getParentId(self.dungeonId), "name");
    titleLabel:setString(dungeonName);
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 设置Google排行榜图标显隐
    local sdkLeaderoardImg = findChildByName(self.node, "BT/sdk_leaderboad");
    if self:isShowSdkLeaderboard() then
        sdkLeaderoardImg:setVisible(true);
    else
        sdkLeaderoardImg:setVisible(false);
    end
end

-- 初始化排行榜
function UIRankingList:init(showEffect)
    local clearTimeLabel = findChildByName(self.node, "CT/clear_time");

    -- 绘制排行榜
    local scrollview = findChildByName(self.node, "CT/scrollview");
    scrollview:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/dungeon/RankingListItem.csb");
    local widget = replaceNodeWithWidget(itemNode);

    -- 获取子区域列表
    local topList = self:getTopList();

    if #topList < 1 then
        clearTimeLabel:setVisible(false);
        return;
    end
    clearTimeLabel:setString("");
    clearTimeLabel:setVisible(true);

    -- 左边距
    local leftMargin = 30;

    -- 行间距
    local gap = 4;
    local widgetHeight = 109;

    local totalNum = #topList;
    self.totalNum = totalNum;

    local startHeight = 0;

    -- 计算总高度
    local totalHeight = totalNum * (widgetHeight + gap);
    startHeight = totalHeight;
    if totalHeight < scrollview:getInnerContainerSize().height then
        startHeight = scrollview:getInnerContainerSize().height;
    end

    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width, math.max(totalHeight, scrollview:getInnerContainerSize().height)));

    self.items = {};
    local i = 1;
    for _, info in pairs(topList) do
        local child = widget:clone();
        local x = leftMargin;

        local y = startHeight - i * (widgetHeight + gap);

        child:setPositionX(x);
        child:setPositionY(y);

        table.insert(self.items, child);

        -- 初始化奖励
        child:setTag(i);
        self:initItem(child, info);

        scrollview:addChild(child);
        i = i + 1;
    end

    if showEffect and self.flyFlag then
        local list = {};
        for j =1, #self.items, 1 do
            table.insert(list, self.items[j]);
        end
        commonScrollItemFlyIn(list);
        self.flyFlag = false;
    end

    -- 时间描述
    local function remainTimeToString(iTime)
        local remainingStr = "";
        if iTime >= 86400 then
            -- "xx天"
            remainingStr = string.format(getLocStr("reset_days"), math.floor(iTime / 86400));
        elseif iTime >= 3600 then
            -- "xx小时"
            remainingStr = string.format(getLocStr("reset_hour"), math.floor(iTime / 3600));
        elseif iTime >= 60 then
            -- "xx分钟"
            remainingStr = string.format(getLocStr("reset_minute"), math.floor(iTime / 60));
        else
            -- "xx秒"
            remainingStr = string.format(getLocStr("reset_second"), iTime);
        end

        return remainingStr;
    end

    -- 绘制重置时间
    local function tick()
        local clearTimeLabel = findChildByName(self.node, "CT/clear_time");
        local remainingTime = TopM.getRemainingTime();

        if remainingTime < 0 then
            clearTimeLabel:setString("");
            clearTimeLabel:setVisible(false);

            -- 重现获取下数据
            Operation.cmd_get_top_list(self.dungeonId);
        else
            local remainingStr = remainTimeToString(remainingTime);
            TextStyleM.setTextStyle(clearTimeLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_YELLOW, true, -3);
            clearTimeLabel:setString(string.format(getLocStr("ranking_list_reset_time"), remainingStr));

            performWithDelay(self, tick, 1);
        end
    end

    tick();
end

-- 初始化排行榜的项目
function UIRankingList:initItem(node, info)
    -- 层数信息
    local layerLabel = findChildByName(node, "layer_label");
    TextStyleM.setTextStyle(layerLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_ORANGE, true, -2);
    TextStyleM.setOutlineStyle(layerLabel, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
    layerLabel:setString(string.format("%s%s", tostring(info["layer"]), getLocStr("dungeon_layer")));

    -- 积分
    local integrationLabel = findChildByName(node, "integration_label");
    TextStyleM.setTextStyle(integrationLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -2);
    TextStyleM.setOutlineStyle(integrationLabel, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
    integrationLabel:setString(getLocStr("dungeon_score"));

    -- 积分数
    local integrationNum = findChildByName(node, "integration_num");
    TextStyleM.setTextStyle(integrationNum, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -2);
    TextStyleM.setOutlineStyle(integrationNum, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
    integrationNum:setString(tostring(info["score"]));

    -- 名字
    local nameLabel = findChildByName(node, "name_label");
    nameLabel:setString(getNickName(tostring(info["name"])));
    nameLabel:setFontSize(TextStyleM.TEXT_SIZE_SMALL2);
    nameLabel:setTextColor(TextStyleM.TEXT_COLOR_CREAM);

    -- 排名
    local rank = node:getTag();

    local placeImg = findChildByName(node, "place_icon");
    placeImg:setVisible(false);
    if rank ~= nil then
        if rank < 4 and rank > 0 then
            placeImg:setVisible(true);
            local iconPath   = getTopListIcon("place" .. rank);
            placeImg:loadTexture(iconPath);
        end
    end

    -- 国籍
    local nation = findChildByName(node, "bg/nationality");
    local nationId = info["nation_id"] or TopM.getDefaultNationId();
    local icon = TopM.queryNationality(nationId, "icon");
    local nationImgPath = getNationalityIconPath(icon);
    nation:loadTexture(nationImgPath);

    -- 出战的冈布奥
    local activePet = findChildByName(node, "hero_icon");
    local petId = info["activity_pet"];
    local icon = PetM.getDefaultIcon(petId);

    local costumeId = info["activity_costume"] or 0;
    if costumeId > 0 and ServerStatusM.query(MODULE_SWITCH_OPEN_COSTUME) == 1 then
        local modelId = EquipM.queryPetModelID(costumeId);
        icon = PetM.queryModel(modelId, "icon");
    end

    local iconPath = getHeroIconPath(icon);
    activePet:loadTexture(iconPath);

    -- 灵魂链接冈布奥
    local imgLictorPet1 = findChildByName(node, "lictor_icon1");
    local imgLictorPet2 = findChildByName(node, "lictor_icon2");
    local lictorPetId1 = info["lictor_pet1"];
    local lictorPetId2 = info["lictor_pet2"];

    if lictorPetId1 ~= nil and lictorPetId1 ~= 0 then
        local icon1 = PetM.getDefaultIcon(lictorPetId1);
        local lictorCostume1 = info["lictor_pet_costume1"] or 0;
        if lictorCostume1 > 0 and ServerStatusM.query(MODULE_SWITCH_OPEN_COSTUME) == 1 then
            local modelId = EquipM.queryPetModelID(lictorCostume1);
            icon1 = PetM.queryModel(modelId, "icon");
        end
        imgLictorPet1:loadTexture(getSmallHeroIconPath(icon1));
        imgLictorPet1:setVisible(true);
    else
        imgLictorPet1:setVisible(false);
    end

    if lictorPetId2 ~= nil and lictorPetId2 ~= 0 then
        local icon2 = PetM.getDefaultIcon(lictorPetId2);
        local lictorCostume2 = info["lictor_pet_costume2"] or 0;
        if lictorCostume2 > 0 and ServerStatusM.query(MODULE_SWITCH_OPEN_COSTUME) == 1 then
            local modelId = EquipM.queryPetModelID(lictorCostume2);
            icon2 = PetM.queryModel(modelId, "icon");
        end
        imgLictorPet2:loadTexture(getSmallHeroIconPath(icon2));
        imgLictorPet2:setVisible(true);
    else
        imgLictorPet2:setVisible(false);
    end
end

function UIRankingList:getTopList()
    -- 获取排行榜信息
    local info = TopM.getTopData(self.dungeonId);
    return info;
end

-- 注册函数回调
function UIRankingList:registerEventCallback()
    -- 关注G+账号登录成功的事件
    EventMgr.register("UIRankingList", event.GOOGLE_CONNECTED, function()
        if self.needShowSdkLeaderboard then
            -- 显示排行榜
            local leaderboardId = GoogleLeaderboardM.queryIdbyField("area_id", self.dungeonId);
            GoogleLeaderboardM.displayLeaderboard(leaderboardId);
            self.needShowSdkLeaderboard = false;
        end
    end);

    -- 关注第三方账号登录成功的事件
    EventMgr.register("UIRankingList", event.THIRD_ACCOUNT_LOGINED, function(para)
        local channel = para.channel;
        if channel == CHANNEL_AMAZON then
            if para.agsReady ~= "1" then
                -- GameCircle尚未准备完毕
                return;
            end

            if self.needShowSdkLeaderboard then
                -- 显示亚马逊排行榜
                local leaderboardId = AmazonLeaderboardM.queryIdbyField("area_id", self.dungeonId);
                AmazonLeaderboardM.displayLeaderboard(leaderboardId);
                self.needShowSdkLeaderboard = false;
            end
        end
    end);

    -- 关注亚马逊GameCircle准备完毕的事件
    EventMgr.register("UIRankingList", event.GAME_CIRCLE_READY, function()
        if self.needShowSdkLeaderboard then
            -- 显示亚马逊排行榜
            local leaderboardId = AmazonLeaderboardM.queryIdbyField("area_id", self.dungeonId);
            AmazonLeaderboardM.displayLeaderboard(leaderboardId);
            self.needShowSdkLeaderboard = false;
        end
    end);

    -- 关注排行榜list
    EventMgr.register("UIRankingList", event.TOP_DATA_UPDATED, function()
        -- 刷新排行榜
        self:init(true);
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIRankingList 界面析构清理");
            EventMgr.removeAll("UIRankingList");

            local dungeonId = self.dungeonId;
            local function showAreaList()
                if ME and ME.isInGame then
                    local uiSubAreaList = UISubAreaList.create(dungeonId);
                    UIMgr.getCurrentScene():addForm(uiSubAreaList);
                end
            end

            performWithDelay(UIMgr.getCurrentScene(), showAreaList, 0.01);
        elseif ev == "enter" then
            UIMgr.getCurrentScene():removeFormByName("UISubAreaList");
        end
    end);

    -- 关注修改国籍
    EventMgr.register("UIRankingList", event.SELECT_NATION, function(args)
        -- 先在客户端修改数据
        local rid = ME.user.rid;
        TopM.changeNation(rid, self.dungeonId, args.id);

        -- 提示修改国家成功
        alert(getLocStr("change_nation_success"));

        -- 重绘当前界面
        self:init();

        -- 向服务端发送修改当前玩家国籍的
        Operation.cmd_change_rank_nation(args.id);
    end);
end
